package worker;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExecuteFile {
	public static void main(String args[]) {
		String inputfile = args[0];
		String lineStr = null;
		String outputfile = inputfile + ".out";
		String errorfile = inputfile + ".err";

		if (args == null || args.length == 0) {
			System.out.println("There is no any execution command.");
		} else {
			try {
				String cmd = "java worker."+inputfile;
				for (int i = 1; i < args.length; i++)
					cmd += " " + args[i];
//				Process p = Runtime.getRuntime().exec(cmd);
				Process p = Runtime.getRuntime().exec("java worker.HelloWorld Melbourne");

				BufferedInputStream in = new BufferedInputStream(p.getInputStream());
				BufferedInputStream err = new BufferedInputStream(p.getErrorStream());
				BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
				BufferedReader errBr = new BufferedReader(new InputStreamReader(err));

				FileOutputStream fos = new FileOutputStream(outputfile);
				// read the output from the command
				while ((lineStr = inBr.readLine()) != null) {
					System.out.println(lineStr);
					fos.write(lineStr.getBytes());
				}
				fos.close();

				fos = new FileOutputStream(errorfile);
				// read any errors from the attempted command
				while ((lineStr = errBr.readLine()) != null) {
					System.out.println(lineStr);
					fos.write(lineStr.getBytes());
				}
				fos.close();

				try {
					if (p.waitFor()!=0) {
						if(p.exitValue()==1)
							System.err.println("fail!");
					}
				}catch (InterruptedException e){
					e.printStackTrace();
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
